package com.linciping.useges.plugin.view;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.*;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;

import javax.swing.*;
import javax.swing.tree.TreeModel;
import java.awt.*;

public class UsegesWindowUtil {

    public static String getWindowId() {
        return "useges_window";
    }

    public static Icon getWindowIcon() {
        return AllIcons.Toolwindows.ToolWindowFind;
    }

    public static ToolWindowFactory getWindowFactory(final TreeModel treeModel) {
        return (project, toolWindow) -> {
            toolWindow.getContentManager().addContent(createToolWindowContent(treeModel));
        };
    }

    public static Content createToolWindowContent(final TreeModel treeModel) {
        UsegesView usegesView = new UsegesView(treeModel);
        ContentFactory contentFactory = ContentFactory.SERVICE.getInstance();
        return contentFactory.createContent(usegesView.getContent(), "", false);
    }

    public static RegisterToolWindowTask getRegisterToolWindowTask(final TreeModel treeModel) {
        return RegisterToolWindowTask.lazyAndClosable(getWindowId(), getWindowFactory(treeModel), getWindowIcon(), ToolWindowAnchor.RIGHT);
    }


    public static void showUsegesWindow(Project project, final TreeModel treeModel) {
        ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(getWindowId());
        if (toolWindow == null) {
            ToolWindowManager.getInstance(project).registerToolWindow(getRegisterToolWindowTask(treeModel)).show();
        } else {
            int contentSize = toolWindow.getContentManager().getContentCount();
            if (contentSize == 0) {
                toolWindow.getContentManager().addContent(createToolWindowContent(treeModel));
            } else {
                Content content = toolWindow.getContentManager().getContent(contentSize - 1);
                if (content != null) {
                    JComponent component = content.getComponent();
                    JTree jTree = findTreeView(component);
                    if (jTree != null) {
                        jTree.setModel(treeModel);
                    }
                }
            }
        }
    }

    private static JTree findTreeView(Container container) {
        if (container == null) return null;
        Component[] components = container.getComponents();
        if (components.length == 0) return null;
        for (Component component : components) {
            if (component instanceof JTree) {
                return (JTree) component;
            } else if (component instanceof Container) {
                return findTreeView((Container) component);
            }
        }
        return null;
    }
}
